package ch.usi.inf.pf2.gui.listener;

import java.awt.Window;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JOptionPane;

import ch.usi.inf.pf2.gui.JSpreadSheetGUI;
import ch.usi.inf.pf2.gui.SpreadSheetFileManager;

/**
 * 
 * @author Lorenzo Baracchi <lorenzo.baracchi@usi.ch>, Ebrisa Savina Mastrodicasa, (Thomas Mantegazzi only for some fixes)
 *
 */

public class CloseActionListener implements ActionListener
{
	private JSpreadSheetGUI spreadTable;
	private JFrame myFrame;

	public CloseActionListener (JSpreadSheetGUI spreadTable)
	{
		this.spreadTable=spreadTable;
		this.myFrame = spreadTable.getFrame();
	}

	@Override
	public void actionPerformed(ActionEvent e)
	{

		if (spreadTable.getSheet().getHasBeenSaved()) {
				myFrame.dispose();
		} else {
			int choice = JOptionPane
			.showOptionDialog(spreadTable.getFrame(),
					"Do you want to save the file?",
					"SpreadSheet - "
					+ spreadTable.getSheet().getName(),
					JOptionPane.YES_NO_CANCEL_OPTION,
					JOptionPane.QUESTION_MESSAGE, new ImageIcon("Icons/question.gif"), null,
					null);
			if (choice == JOptionPane.CANCEL_OPTION) {

			} else if(choice == JOptionPane.CLOSED_OPTION)
			{
				
			} else if (choice == JOptionPane.NO_OPTION) {
				myFrame.dispose();
			} else {
				SpreadSheetFileManager.saveAsFile(spreadTable
						.getSheet(), spreadTable.getSheet().getName());
				spreadTable.getSheet().setName(
						spreadTable.getSheet().getName());
				myFrame.dispose();
			}
		}
	}
}
